package proxy

import (
	"fmt"
	"sync"
	"time"
)

// 以敏感数据查询为例

// 抽象主题
type DataQuery interface {
	Query(user string, keyword string) (string, error)
}

// 具体主题
type SensitiveDataService struct {
}

func (s *SensitiveDataService) Query(user string, keyword string) (string, error) {
	// 模拟数据库查询
	fmt.Printf("执行核心查询: 用户[%s] 查询[%s]\n", user, keyword)
	return fmt.Sprintf("%s的查询结果：机密数据-%d", user, time.Now().Unix()), nil
}

type DataQueryProxy struct {
	realService   DataQuery
	cache         map[string]string
	accessRecords map[string]time.Time
	mutex         sync.Mutex
}

func NewDataQueryProxy() *DataQueryProxy {
	return &DataQueryProxy{
		realService:   &SensitiveDataService{},
		cache:         make(map[string]string),
		accessRecords: make(map[string]time.Time),
	}
}

func (s *DataQueryProxy) Query(user string, keyword string) (string, error) {
	startTime := time.Now()

	// 权限验证
	if !s.checkPermission(user) {
		return "", fmt.Errorf("用户[%s]无权限查询", user)
	}
	// 限流控制
	if !s.rateLimit(user) {
		return "", fmt.Errorf("用户[%s]请求过于频繁", user)
	}
	if result, ok := s.cache[keyword]; ok {
		// 命中缓存
		fmt.Printf("命中缓存: 用户[%s] 查询[%s]\n", user, keyword)
		return result, nil
	}

	// 未命中缓存
	result, err := s.realService.Query(user, keyword)
	if err != nil {
		return "", err
	}
	s.mutex.Lock()
	s.cache[keyword] = result
	s.mutex.Unlock()

	// 记录日志
	fmt.Printf("执行核心查询: 用户[%s] 查询[%s] 耗时: %v\n", user, keyword, time.Since(startTime))
	return result, nil
}

func (s *DataQueryProxy) checkPermission(user string) bool {
	// 模拟权限验证逻辑
	return user == "admin" || user == "auditor"
}

func (s *DataQueryProxy) rateLimit(user string) bool {
	s.mutex.Lock()
	defer s.mutex.Unlock()

	lastAccess, exists := s.accessRecords[user]
	if exists && time.Since(lastAccess) < time.Second {
		return false
	}
	s.accessRecords[user] = time.Now()
	return true
}
